afyx-engineering-kit 0.1.0-alpha.7 → 0.1.0-alpha.8

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 (55) hide show
  1. package/.afyx-source-revision +1 -1
  2. package/afyx-context/src/budget.js +39 -153
  3. package/afyx-context/src/documentation.js +116 -0
  4. package/afyx-context/src/index.js +2 -0
  5. package/afyx-context/src/memory.js +122 -229
  6. package/afyx-context/src/usage.js +91 -0
  7. package/afyx-forge/src/cli.js +14 -1
  8. package/afyx-forge/src/index.js +3 -0
  9. package/afyx-forge/src/workflow-refiner.js +48 -15
  10. package/afyx-forge/src/workflow.js +226 -0
  11. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +16 -6
  12. package/afyx-graph/engine/release/SHA256SUMS +4 -2
  13. package/afyx-graph/engine/release/afyx-graph-darwin-arm64.tar.gz +0 -0
  14. package/afyx-graph/engine/release/afyx-graph-darwin-x64.tar.gz +0 -0
  15. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  16. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  17. package/bin/afyx-engineering-kit.mjs +14 -6
  18. package/install.ps1 +52 -6
  19. package/install.sh +11 -7
  20. package/package.json +3 -1
  21. package/scripts/afyx-capability-orchestrator.mjs +159 -41
  22. package/scripts/afyx-graph-artifact.mjs +1 -1
  23. package/scripts/afyx-graph-targets.mjs +8 -0
  24. package/scripts/afyx-host-adapters.mjs +52 -0
  25. package/scripts/afyx-host-bridge-lifecycle.mjs +4 -0
  26. package/scripts/afyx-host-bridge.mjs +25 -0
  27. package/scripts/afyx-install-backend.mjs +34 -13
  28. package/scripts/afyx-install-contract.mjs +5 -2
  29. package/scripts/afyx-install-progress.mjs +88 -0
  30. package/scripts/afyx-installer-environment.mjs +150 -0
  31. package/scripts/afyx-local-link-ownership.mjs +16 -0
  32. package/scripts/afyx-midnight-circuit.mjs +322 -79
  33. package/scripts/afyx-modular-integration.mjs +3 -0
  34. package/scripts/afyx-modular-runtime.mjs +3 -0
  35. package/scripts/afyx-native-execution.mjs +168 -0
  36. package/scripts/afyx-native-github.mjs +155 -0
  37. package/scripts/afyx-npm-installer.mjs +56 -28
  38. package/scripts/afyx-provider-inventory.mjs +6 -3
  39. package/scripts/afyx-security-auditor.mjs +61 -64
  40. package/scripts/afyx-skill-catalog.mjs +83 -0
  41. package/scripts/afyx-skill-engineering.mjs +2 -0
  42. package/scripts/afyx-universal-runtime.mjs +74 -12
  43. package/scripts/install-afyx-graph.sh +4 -4
  44. package/scripts/lib/AfyxInstallerProgress.psm1 +11 -0
  45. package/scripts/lib/AfyxSkillLifecycle.psm1 +42 -6
  46. package/scripts/lib/afyx-installer-progress.sh +30 -0
  47. package/scripts/link-global-dev.ps1 +10 -3
  48. package/scripts/link-global-dev.sh +10 -8
  49. package/scripts/prepare-g6-package.mjs +13 -28
  50. package/scripts/resolve-git-release-artifacts.mjs +5 -4
  51. package/scripts/stage-npm-release.mjs +3 -1
  52. package/scripts/validate-release-zip-graph.mjs +2 -2
  53. package/uninstall.ps1 +2 -0
  54. package/verify.ps1 +7 -1
  55. package/verify.sh +5 -3
@@ -69,6 +69,7 @@ const AUTONOMOUS_FORGE_INTENTS = new Set([
69
69
  'formal-forge-evaluation',
70
70
  'production-forge-execution',
71
71
  ]);
72
+ const FOLLOW_UP_JUSTIFICATION = Symbol('host-adapter-justification');
72
73
 
73
74
  /** In-memory dynamic component registry for universal extensibility. */
74
75
  const DYNAMIC_COMPONENT_REGISTRY = new Map(Object.entries(PRODUCT_INVENTORY));
@@ -126,14 +127,14 @@ function normalizeBudgets(requested = {}) {
126
127
  });
127
128
  }
128
129
 
129
- function providerAllows(componentId, capability, provider, providerPermissions) {
130
+ function providerAllows(componentId, capability, provider, providerPermissions, metadata) {
130
131
  if (providerPermissions?.[componentId] === false || providerPermissions?.[capability] === false) {
131
132
  return false;
132
133
  }
133
134
  if (provider === null) return componentId !== 'afyx-credential-broker';
134
135
  const providerMeta = PROVIDER_CAPABILITY_SUPPORT[provider];
135
136
  if (!providerMeta) return false;
136
- const declaredProviders = DYNAMIC_COMPONENT_REGISTRY.get(componentId)?.providers;
137
+ const declaredProviders = metadata?.providers;
137
138
  if (declaredProviders && !declaredProviders.includes(provider)) return false;
138
139
  if (componentId === 'afyx-forge') {
139
140
  return providerPermissions?.[componentId] === true;
@@ -167,21 +168,20 @@ export function discoverAfyxCapabilities({
167
168
  const contextEnvironmentOff = String(environment?.AFYX_CONTEXT_OPT_IN ?? '').trim() === '0';
168
169
  const capabilities = {};
169
170
 
170
- if (Array.isArray(customComponents)) {
171
- for (const comp of customComponents) {
172
- if (comp?.id) registerAfyxComponent(comp);
173
- }
171
+ const localRegistry = new Map(DYNAMIC_COMPONENT_REGISTRY);
172
+ for (const item of Array.isArray(customComponents) ? customComponents : []) {
173
+ if (item?.id && typeof item.id === 'string') localRegistry.set(item.id, Object.freeze({ ...item }));
174
174
  }
175
175
 
176
176
  // Universal discovery over all registered and caller-declared components
177
177
  const allComponentIds = new Set([
178
- ...DYNAMIC_COMPONENT_REGISTRY.keys(),
178
+ ...localRegistry.keys(),
179
179
  ...Object.keys(componentStates),
180
180
  ]);
181
181
 
182
182
  for (const componentId of allComponentIds) {
183
183
  const observed = componentStates[componentId] ?? {};
184
- const metadata = DYNAMIC_COMPONENT_REGISTRY.get(componentId) ?? {
184
+ const metadata = localRegistry.get(componentId) ?? {
185
185
  id: componentId,
186
186
  canonicalName: observed.canonicalName ?? componentId,
187
187
  type: observed.type ?? 'runtime',
@@ -197,6 +197,7 @@ export function discoverAfyxCapabilities({
197
197
  capability,
198
198
  normalizedProvider,
199
199
  providerPermissions,
200
+ metadata,
200
201
  );
201
202
  const installed = observed.installed === true;
202
203
  // Default-enabled for interoperability if installed, unless explicitly set to false or context env off
@@ -248,31 +249,50 @@ export function discoverAfyxCapabilities({
248
249
  }
249
250
 
250
251
  /** Cheap deterministic task classification. */
251
- export function classifyTaskIntent(task = {}) {
252
+ export function classifyTaskIntent(task = {}, hostMetadata = {}) {
253
+ // Host observations are routing hints, never authorization grants. Task JSON
254
+ // cannot supply the in-process hostMetadata or a schema loader.
255
+ const domain = String(task.domain ?? hostMetadata.domain ?? '').toLowerCase();
256
+ const knownDomains = new Set(['odoo', 'github', 'documentation', 'local-cli', 'engineering', 'security']);
257
+ const unknownDomain = Boolean(domain && !knownDomains.has(domain));
258
+ const framework = task.project?.framework ?? task.framework ?? hostMetadata.project?.framework ?? hostMetadata.file?.framework;
252
259
  const intentText = `${task.intent ?? ''} ${task.operation ?? ''}`.toLowerCase();
253
260
  const taskType = String(task.taskType ?? 'generic').toLowerCase();
261
+ const textualDomains = [/\bodoo\b/, /\bgithub\b/, /\bdocumentation\b/].filter((pattern) => pattern.test(intentText));
262
+ const specifiedType = taskType !== 'generic' && taskType !== 'unknown';
263
+ const ambiguousDomain = !domain && !specifiedType && (textualDomains.length > 1 ||
264
+ (Array.isArray(hostMetadata.domains) && new Set(hostMetadata.domains).size > 1));
254
265
  const directSourceCandidate = task.exactKnownSource === true || task.knownFile === true ||
255
266
  ['known-file', 'string-replacement', 'exact-source'].includes(taskType) ||
256
267
  /\b(exact source|known file|string replacement)\b/.test(intentText);
257
- const odoo = task.project?.isOdoo === true || task.explicitOdooEvidence === true ||
258
- taskType.startsWith('odoo-') || /\bodoo\b/.test(intentText);
268
+ const specializedType = ['github-operation', 'documentation-search', 'documentation-research', 'multi-agent-workflow', 'workflow-execution', 'cli-automation'].includes(taskType);
269
+ const odoo = (!domain || domain === 'odoo') && !ambiguousDomain && (domain === 'odoo' || !specializedType && (framework === 'odoo' ||
270
+ task.project?.isOdoo === true || task.explicitOdooEvidence === true || taskType.startsWith('odoo-') || /\bodoo\b/.test(intentText)));
259
271
  const relational = task.needsRelationalEvidence === true ||
260
272
  ['impact-analysis', 'cross-asset', 'relationship-analysis'].includes(taskType) ||
261
273
  /\b(dependency|relationship|blast radius|call graph|impact analysis)\b/.test(intentText);
262
274
  const contextOptimization = task.needsContextOptimization === true ||
263
275
  taskType === 'large-context';
264
- const architecture = ['architecture', 'multi-disciplinary', 'system-design'].includes(taskType);
265
- const forgeAdvice = task.forgeAdvice === true || taskType === 'forge-advice';
276
+ const architecture = ['architecture', 'multi-disciplinary', 'system-design', 'general-engineering', 'skill-discovery', 'skill-refinement', 'skill-composition'].includes(taskType);
277
+ const forgeAdvice = task.forgeAdvice === true || ['forge-advice', 'workflow-execution', 'multi-agent-workflow'].includes(taskType);
266
278
  const forgeAutonomous = task.autonomousExecution === true || AUTONOMOUS_FORGE_INTENTS.has(taskType);
267
279
  const telemetry = task.needsTelemetry === true || task.telemetry === true || task.trackUsage === true ||
268
280
  taskType === 'usage-telemetry' || taskType === 'telemetry' ||
269
281
  /\b(telemetry|usage tracking|usage report)\b/.test(intentText);
282
+ const documentation = ['documentation-search', 'documentation-research'].includes(taskType) || domain === 'documentation';
283
+ const usageAnalytics = taskType === 'usage-analytics';
284
+ const github = taskType !== 'cli-automation' && (taskType === 'github-operation' || domain === 'github');
285
+ const nativeExecution = taskType === 'cli-automation' || domain === 'local-cli';
286
+ const securityAudit = taskType === 'security-audit';
287
+ const manualSelection = Array.isArray(task.manualSelection) ? task.manualSelection.filter((id) => typeof id === 'string').slice(0, 4) : [];
270
288
  const customCapability = task.needsCustomCapability ?? task.customCapability ?? null;
271
289
  const customComponentId = task.customComponentId ?? null;
272
- const complexCapabilityNeeded = odoo || relational || contextOptimization ||
273
- architecture || forgeAdvice || forgeAutonomous || telemetry ||
274
- Boolean(customCapability) || Boolean(customComponentId);
275
- const directSource = directSourceCandidate && !complexCapabilityNeeded;
290
+ const explicitSharedNeed = task.needsRelationalEvidence === true || task.needsContextOptimization === true;
291
+ const explicitCapabilityType = taskType.startsWith('odoo-') || specializedType || securityAudit || architecture ||
292
+ ['large-context', 'usage-telemetry', 'usage-analytics', 'impact-analysis', 'cross-asset', 'relationship-analysis'].includes(taskType);
293
+ const explicitTelemetry = task.needsTelemetry === true || task.telemetry === true || task.trackUsage === true;
294
+ const directSource = directSourceCandidate && !explicitSharedNeed && !explicitCapabilityType && !manualSelection.length &&
295
+ !forgeAdvice && !forgeAutonomous && !explicitTelemetry && !customCapability && !customComponentId;
276
296
 
277
297
  return Object.freeze({
278
298
  directSource,
@@ -284,7 +304,8 @@ export function classifyTaskIntent(task = {}) {
284
304
  forgeAutonomous,
285
305
  telemetry,
286
306
  customCapability,
287
- customComponentId,
307
+ customComponentId, documentation, usageAnalytics, github, nativeExecution, securityAudit, manualSelection,
308
+ unknownDomain, ambiguousDomain,
288
309
  });
289
310
  }
290
311
 
@@ -316,17 +337,26 @@ function makeRequest({ task, componentId, discovery, budgets, reason, hopCount =
316
337
  hopCount,
317
338
  invocationReason: reason,
318
339
  sourceIdentity: discovered.sourceIdentity,
319
- payload: typeof task.payload === 'string' ? task.payload : (typeof task.text === 'string' ? task.text : (typeof task.input === 'string' ? task.input : null)),
340
+ // Structured task data is not host configuration or an authorization grant.
341
+ payload: task.payload !== null && typeof task.payload === 'object' ? task.payload
342
+ : typeof task.payload === 'string' ? task.payload : (typeof task.text === 'string' ? task.text : (typeof task.input === 'string' ? task.input : null)),
320
343
  classification: typeof task.classification === 'string' ? task.classification : null,
321
344
  });
322
345
  }
323
346
 
324
347
  function selectionCandidates(task, classification, modularRuntimePlan, discovery) {
325
348
  if (classification.directSource) return [];
326
- const selectedByPlanner = new Set(modularRuntimePlan.plannedComponents);
349
+ const exclusiveDomain = classification.odoo || classification.forgeAdvice || classification.documentation || classification.usageAnalytics || classification.github || classification.nativeExecution || classification.securityAudit || classification.unknownDomain || classification.ambiguousDomain;
350
+ const selectedByPlanner = new Set(exclusiveDomain ? [] : modularRuntimePlan.plannedComponents);
351
+ if (classification.documentation || classification.usageAnalytics) selectedByPlanner.add('afyx-context');
352
+ if (classification.github) selectedByPlanner.add('afyx-native-github');
353
+ if (classification.nativeExecution) selectedByPlanner.add('afyx-native-execution');
354
+ if (classification.securityAudit) selectedByPlanner.add('afyx-security-auditor');
355
+ for (const id of classification.manualSelection) selectedByPlanner.add(id);
356
+
327
357
  if (classification.odoo) selectedByPlanner.add('odoo-engineering');
328
358
  if (classification.architecture) selectedByPlanner.add('afyx-engineering-expert');
329
- if (classification.relational) selectedByPlanner.add('afyx-graph');
359
+ if (classification.relational && (!exclusiveDomain || task.needsRelationalEvidence === true)) selectedByPlanner.add('afyx-graph');
330
360
  if (classification.contextOptimization) selectedByPlanner.add('afyx-context');
331
361
  if (classification.forgeAdvice && !classification.forgeAutonomous) {
332
362
  selectedByPlanner.add('afyx-forge');
@@ -346,6 +376,11 @@ function selectionCandidates(task, classification, modularRuntimePlan, discovery
346
376
  }
347
377
 
348
378
  const preferredOrder = [
379
+ ...(classification.documentation || classification.usageAnalytics ? ['afyx-context'] : []),
380
+ ...(classification.github ? ['afyx-native-github'] : []),
381
+ ...(classification.nativeExecution ? ['afyx-native-execution'] : []),
382
+ ...(classification.securityAudit ? ['afyx-security-auditor'] : []),
383
+ ...classification.manualSelection,
349
384
  ...(classification.odoo ? ['odoo-engineering'] : []),
350
385
  ...(classification.architecture ? ['afyx-engineering-expert'] : []),
351
386
  ...(classification.relational ? ['afyx-graph'] : []),
@@ -378,7 +413,7 @@ export function resolveAfyxCapabilityRoute(options = {}) {
378
413
  const task = options.task ?? {};
379
414
  const budgets = normalizeBudgets(options.budgetLimits);
380
415
  const discovery = discoverAfyxCapabilities(options);
381
- const classification = classifyTaskIntent(task);
416
+ const classification = classifyTaskIntent(task, options.hostMetadata);
382
417
  const modularRuntimePlan = resolveModularRuntimeActivation({
383
418
  task,
384
419
  provider: options.provider ?? null,
@@ -396,6 +431,10 @@ export function resolveAfyxCapabilityRoute(options = {}) {
396
431
  const seenCapabilities = new Set();
397
432
  const owners = {};
398
433
 
434
+ if (classification.unknownDomain || classification.ambiguousDomain) {
435
+ diagnostics.push({ code: classification.unknownDomain ? 'UNKNOWN_DOMAIN' : 'AMBIGUOUS_DOMAIN', severity: 'INFO' });
436
+ }
437
+
399
438
  if (!discovery.providerKnown) {
400
439
  diagnostics.push({ code: 'UNKNOWN_PROVIDER', severity: 'ERROR' });
401
440
  }
@@ -428,6 +467,10 @@ export function resolveAfyxCapabilityRoute(options = {}) {
428
467
  diagnostics.push({ code: 'AUTHORITY_MISMATCH', componentId, severity: 'ERROR' });
429
468
  continue;
430
469
  }
470
+ if (owners[discovered.capability] && owners[discovered.capability] !== componentId) {
471
+ diagnostics.push({ code: 'AUTHORITY_CONFLICT', capability: discovered.capability, severity: 'ERROR' });
472
+ continue;
473
+ }
431
474
  owners[discovered.capability] = componentId;
432
475
  if (!discovered.available) {
433
476
  degradations.push({
@@ -458,7 +501,8 @@ export function resolveAfyxCapabilityRoute(options = {}) {
458
501
  requests.push(makeRequest({ task, componentId, discovery, budgets, reason }));
459
502
  }
460
503
 
461
- const blocked = !discovery.providerKnown || classification.forgeAutonomous || inheritedBlockingDiagnostics.length > 0;
504
+ const blocked = !discovery.providerKnown || classification.forgeAutonomous || inheritedBlockingDiagnostics.length > 0 ||
505
+ diagnostics.some((item) => ['AUTHORITY_CONFLICT', 'AUTHORITY_MISMATCH'].includes(item.code));
462
506
  return Object.freeze({
463
507
  contract: AFYX_UNIVERSAL_INTEROP_CONTRACT,
464
508
  taskId: task.id ?? 'anonymous-task',
@@ -496,6 +540,7 @@ function normalizedAdapterResult(request, raw, durationMs, validTargetIds) {
496
540
  .filter((item) => item && (validTargetIds ? validTargetIds.has(item.targetComponentId) : true))
497
541
  .map((item) => Object.freeze({
498
542
  targetComponentId: item.targetComponentId,
543
+ [FOLLOW_UP_JUSTIFICATION]: typeof item.invocationReason === 'string' && item.invocationReason.trim().length > 0,
499
544
  invocationReason: typeof item.invocationReason === 'string'
500
545
  ? item.invocationReason
501
546
  : `Requested by ${request.targetComponentId}`,
@@ -562,18 +607,37 @@ function failedExecutionResult(request, reason, durationMs) {
562
607
  * bounded by budgets, deduplication, cycle prevention, and Forge A8 restrictions.
563
608
  */
564
609
  export async function executeAfyxCapabilityRoute(options = {}) {
610
+ const executionStarted = performance.now();
611
+ const startedAt = executionStarted - (Number.isFinite(options.preparationElapsedMs) ? Math.max(0, options.preparationElapsedMs) : 0);
565
612
  const route = resolveAfyxCapabilityRoute(options);
613
+ const planningMs = performance.now() - executionStarted;
614
+ let activeDiscovery = route.discovery;
615
+ const activeOwners = { ...route.domainAuthorities };
566
616
  const adapters = options.adapters ?? {};
567
- const startedAt = performance.now();
568
617
  const queue = [...route.requests];
569
618
  const results = [];
570
619
  const seen = new Set();
571
620
  const scheduledComponents = new Set(route.requests.map((request) => request.targetComponentId));
572
621
  const validTargetIds = new Set(Object.keys(route.discovery.capabilities));
622
+ const preparedCapabilities = new Set();
573
623
  let contextBytes = 0;
574
624
  let duplicateInvocationsAvoided = 0;
575
625
  let toolCalls = 0;
576
626
  let contextBudgetExceeded = false;
627
+ const invokedTools = [], loadedTools = [], details = new Map();
628
+ const justified = new Set(route.requests.map((request) => request.targetComponentId));
629
+ let schemaBytes = 0, schemaLatencyMs = 0, activeSchemaStarted = null, schemaLoadCalls = 0, blockedOutOfScopeRequests = 0;
630
+ const routingMetrics = () => ({
631
+ registeredTools: Object.keys(route.discovery.capabilities),
632
+ discoveredTools: Object.values(route.discovery.capabilities).filter((item) => item.installed && item.enabled).map((item) => item.componentId),
633
+ selectedTools: route.requests.map((request) => request.targetComponentId),
634
+ invokedTools: [...invokedTools], loadedTools: [...loadedTools], schemaBytes, planningMs, schemaLoadCalls,
635
+ schemaLatencyMs: schemaLatencyMs + (activeSchemaStarted === null ? 0 : performance.now() - activeSchemaStarted),
636
+ unnecessaryInvocationCount: invokedTools.filter((id) => !justified.has(id)).length,
637
+ blockedOutOfScopeRequests,
638
+ detailLoading: typeof options.loadCapabilityDetails === 'function' ? 'HOST_DEFERRED_DETAILS' : 'HOST_NOT_SUPPORTED',
639
+ registrationTokenSavings: 'NOT_CLAIMED',
640
+ });
577
641
 
578
642
  if (route.status === 'BLOCKED' || route.directSourceFastPath) {
579
643
  return Object.freeze({
@@ -581,6 +645,7 @@ export async function executeAfyxCapabilityRoute(options = {}) {
581
645
  executionStatus: route.status === 'BLOCKED' ? 'BLOCKED' : 'DIRECT_SOURCE',
582
646
  results: Object.freeze([]),
583
647
  metrics: Object.freeze({
648
+ ...routingMetrics(),
584
649
  selectedCapabilities: route.requests.length,
585
650
  executedCapabilities: 0,
586
651
  toolCalls: 0,
@@ -613,7 +678,7 @@ export async function executeAfyxCapabilityRoute(options = {}) {
613
678
  results.push(nonExecutedResult(request, 'BLOCKED', 'EXECUTION_TIME_BUDGET_EXHAUSTED'));
614
679
  continue;
615
680
  }
616
- const discovered = route.discovery.capabilities[request.targetComponentId];
681
+ const discovered = activeDiscovery.capabilities[request.targetComponentId];
617
682
  if (!discovered?.available || discovered.capability !== request.capability) {
618
683
  results.push(nonExecutedResult(request, 'BLOCKED', 'CAPABILITY_NOT_AVAILABLE'));
619
684
  continue;
@@ -627,6 +692,7 @@ export async function executeAfyxCapabilityRoute(options = {}) {
627
692
  const invocationStartedAt = performance.now();
628
693
  let result;
629
694
  let timeout;
695
+ let adapterStarted = false;
630
696
  const controller = new AbortController();
631
697
  try {
632
698
  const remainingMs = Math.max(1, route.budgets.maxExecutionMs - (performance.now() - startedAt));
@@ -636,25 +702,46 @@ export async function executeAfyxCapabilityRoute(options = {}) {
636
702
  reject(new Error('EXECUTION_TIME_BUDGET_EXHAUSTED'));
637
703
  }, remainingMs);
638
704
  });
639
- toolCalls += 1;
705
+ const invoke = async () => {
706
+ let capabilityDetails;
707
+ if (typeof options.loadCapabilityDetails === 'function') {
708
+ activeSchemaStarted = performance.now();
709
+ schemaLoadCalls += 1;
710
+ try { capabilityDetails = await options.loadCapabilityDetails(request, { signal: controller.signal }); }
711
+ finally { schemaLatencyMs += performance.now() - activeSchemaStarted; activeSchemaStarted = null; }
712
+ if (controller.signal.aborted) throw new Error('EXECUTION_TIME_BUDGET_EXHAUSTED');
713
+ const encoded = JSON.stringify(capabilityDetails);
714
+ if (!encoded) throw new Error('CAPABILITY_DETAILS_UNAVAILABLE');
715
+ const bytes = Buffer.byteLength(encoded);
716
+ if (schemaBytes + contextBytes + bytes > route.budgets.maxContextBytes) throw new Error('SCHEMA_CONTEXT_BUDGET_EXHAUSTED');
717
+ schemaBytes += bytes;
718
+ // Snapshot host data; adapter mutations cannot affect another request.
719
+ details.set(request.targetComponentId, JSON.parse(encoded));
720
+ loadedTools.push(request.targetComponentId);
721
+ capabilityDetails = details.get(request.targetComponentId);
722
+ }
723
+ if (controller.signal.aborted) throw new Error('EXECUTION_TIME_BUDGET_EXHAUSTED');
724
+ toolCalls += 1;
725
+ adapterStarted = true;
726
+ invokedTools.push(request.targetComponentId);
727
+ return adapter(request, { signal: controller.signal, capabilityDetails });
728
+ };
640
729
  result = normalizedAdapterResult(
641
730
  request,
642
- await Promise.race([adapter(request, { signal: controller.signal }), timeoutPromise]),
731
+ await Promise.race([invoke(), timeoutPromise]),
643
732
  performance.now() - invocationStartedAt,
644
733
  validTargetIds,
645
734
  );
646
735
  } catch (error) {
647
- result = failedExecutionResult(
648
- request,
649
- error instanceof Error ? error.message : String(error),
650
- performance.now() - invocationStartedAt,
651
- );
736
+ const reason = error instanceof Error ? error.message : String(error);
737
+ result = adapterStarted ? failedExecutionResult(request, reason, performance.now() - invocationStartedAt)
738
+ : Object.freeze({ ...nonExecutedResult(request, 'FAILED', reason), durationMs: performance.now() - invocationStartedAt });
652
739
  } finally {
653
740
  clearTimeout(timeout);
654
741
  }
655
742
  results.push(result);
656
743
  contextBytes += result.contextBytes;
657
- if (contextBytes > route.budgets.maxContextBytes) {
744
+ if (contextBytes + schemaBytes > route.budgets.maxContextBytes) {
658
745
  contextBudgetExceeded = true;
659
746
  break;
660
747
  }
@@ -671,30 +758,56 @@ export async function executeAfyxCapabilityRoute(options = {}) {
671
758
  effectiveFollowUps.push({
672
759
  targetComponentId: 'afyx-context',
673
760
  invocationReason: 'Compress large graph evidence payload',
761
+ [FOLLOW_UP_JUSTIFICATION]: true,
674
762
  });
675
763
  }
676
764
 
677
765
  for (const followUp of effectiveFollowUps) {
678
766
  const target = followUp?.targetComponentId;
679
- const followUpCapability = route.discovery.capabilities[target];
767
+ let followUpCapability = activeDiscovery.capabilities[target];
680
768
  const forgeAllowed = target !== 'afyx-forge' ||
681
- (route.classification.forgeAdvice && !route.classification.forgeAutonomous);
682
- const isAvailable = followUpCapability?.available === true;
769
+ ((route.classification.forgeAdvice || route.classification.manualSelection.includes(target)) && !route.classification.forgeAutonomous);
683
770
  const notDirectSelfCycle = target !== request.targetComponentId;
771
+ const authorityOwner = DOMAIN_AUTHORITY_MATRIX[followUpCapability?.capability]?.primaryOwner || activeOwners[followUpCapability?.capability];
772
+ const ownsDomain = !authorityOwner || authorityOwner === target;
773
+ const narrowDomain = route.classification.odoo || route.classification.github || route.classification.documentation || route.classification.nativeExecution ||
774
+ route.classification.relational || route.classification.contextOptimization || route.classification.forgeAdvice;
775
+ const shared = ['afyx-graph', 'afyx-context'].includes(target) && result.status === 'EXECUTED' &&
776
+ followUp[FOLLOW_UP_JUSTIFICATION] === true &&
777
+ (route.classification.odoo || route.classification.relational || route.classification.forgeAdvice || (target === 'afyx-context' && route.classification.contextOptimization) ||
778
+ (target === 'afyx-graph' && options.task?.needsRelationalEvidence === true));
779
+ const inScope = !narrowDomain || justified.has(target) || route.classification.manualSelection.includes(target) || shared;
780
+ if (!inScope) blockedOutOfScopeRequests += 1;
781
+ if (inScope && ownsDomain && forgeAllowed && notDirectSelfCycle && target === 'afyx-graph' &&
782
+ followUpCapability?.reason === 'GRAPH_INDEX_NOT_READY_OR_FRESH' && typeof options.prepareCapabilityState === 'function' &&
783
+ !preparedCapabilities.has(target) && toolCalls < route.budgets.maxToolCalls && request.hopCount < route.budgets.maxHops &&
784
+ (scheduledComponents.has(target) || scheduledComponents.size < route.budgets.maxCapabilities) &&
785
+ performance.now() - startedAt < route.budgets.maxExecutionMs) {
786
+ preparedCapabilities.add(target);
787
+ try {
788
+ const state = await options.prepareCapabilityState(target, { maxExecutionMs: Math.max(1, Math.floor(route.budgets.maxExecutionMs - (performance.now() - startedAt))) });
789
+ const observed = discoverAfyxCapabilities({ ...options, componentStates: { ...options.componentStates, [target]: state } });
790
+ if (observed.capabilities[target]?.sourceIdentity === followUpCapability.sourceIdentity) {
791
+ activeDiscovery = observed;
792
+ followUpCapability = observed.capabilities[target];
793
+ }
794
+ } catch { /* A failed preflight remains unavailable, never assumed fresh. */ }
795
+ }
796
+ const isAvailable = followUpCapability?.available === true;
684
797
 
685
- if (!isAvailable || !forgeAllowed || !notDirectSelfCycle) {
798
+ if (!isAvailable || !forgeAllowed || !notDirectSelfCycle || !inScope || !ownsDomain) {
686
799
  if (followUpCapability) {
687
800
  results.push(nonExecutedResult(
688
801
  makeRequest({
689
802
  task: options.task ?? {},
690
803
  componentId: target,
691
- discovery: route.discovery,
804
+ discovery: activeDiscovery,
692
805
  budgets: route.budgets,
693
806
  reason: followUp.invocationReason ?? `Requested by ${request.targetComponentId}`,
694
807
  hopCount: request.hopCount + 1,
695
808
  }),
696
809
  'BLOCKED',
697
- !forgeAllowed ? 'FORGE_A8_REQUIRED' : (!notDirectSelfCycle ? 'DIRECT_SELF_CYCLE' : 'FOLLOW_UP_NOT_AUTHORIZED'),
810
+ !ownsDomain ? 'FOLLOW_UP_AUTHORITY_CONFLICT' : !inScope ? 'FOLLOW_UP_OUT_OF_SCOPE' : !forgeAllowed ? 'FORGE_A8_REQUIRED' : (!notDirectSelfCycle ? 'DIRECT_SELF_CYCLE' : 'FOLLOW_UP_NOT_AUTHORIZED'),
698
811
  ));
699
812
  }
700
813
  continue;
@@ -704,7 +817,7 @@ export async function executeAfyxCapabilityRoute(options = {}) {
704
817
  makeRequest({
705
818
  task: options.task ?? {},
706
819
  componentId: target,
707
- discovery: route.discovery,
820
+ discovery: activeDiscovery,
708
821
  budgets: route.budgets,
709
822
  reason: followUp.invocationReason ?? `Requested by ${request.targetComponentId}`,
710
823
  hopCount: request.hopCount + 1,
@@ -715,11 +828,13 @@ export async function executeAfyxCapabilityRoute(options = {}) {
715
828
  continue;
716
829
  }
717
830
  scheduledComponents.add(target);
831
+ activeOwners[followUpCapability.capability] = target;
832
+ justified.add(target);
718
833
  queue.push(Object.freeze({
719
834
  ...makeRequest({
720
835
  task: options.task ?? {},
721
836
  componentId: target,
722
- discovery: route.discovery,
837
+ discovery: activeDiscovery,
723
838
  budgets: route.budgets,
724
839
  reason: followUp.invocationReason ?? `Requested by ${request.targetComponentId}`,
725
840
  hopCount: request.hopCount + 1,
@@ -736,10 +851,13 @@ export async function executeAfyxCapabilityRoute(options = {}) {
736
851
  const degraded = contextBudgetExceeded || route.status === 'DEGRADED' || results.some((result) => ['DEGRADED', 'BLOCKED'].includes(result.status));
737
852
  return Object.freeze({
738
853
  ...route,
854
+ discovery: activeDiscovery,
855
+ domainAuthorities: Object.freeze(activeOwners),
739
856
  status: failed ? 'FAILED' : (degraded ? 'DEGRADED' : 'READY'),
740
857
  executionStatus: executedCapabilities > 0 ? 'EXECUTED' : 'NOT_RUN',
741
858
  results: Object.freeze(results),
742
859
  metrics: Object.freeze({
860
+ ...routingMetrics(),
743
861
  selectedCapabilities: route.requests.length,
744
862
  executedCapabilities,
745
863
  toolCalls,
@@ -105,7 +105,7 @@ function verifyReleaseManifest(manifestFile, archiveFile, metadataFile) {
105
105
  const manifest = readMetadata(manifestFile);
106
106
  const metadata = readMetadata(metadataFile);
107
107
  const identity = artifactIdentity(metadata);
108
- if (manifest.schema !== 1 || manifest.product !== 'Afyx Graph') throw new Error('release manifest schema or product mismatch');
108
+ if (![1, 2].includes(manifest.schema) || manifest.product !== 'Afyx Graph') throw new Error('release manifest schema or product mismatch');
109
109
  const name = basename(archiveFile);
110
110
  const entry = Array.isArray(manifest.artifacts) ? manifest.artifacts.find((item) => item.file === name) : null;
111
111
  if (!entry || !/^[0-9a-f]{64}$/i.test(String(entry.sha256 || ''))) throw new Error(`release manifest has no valid entry for ${name}`);
@@ -0,0 +1,8 @@
1
+ /** Kit runtime support is explicit. Schema 1 preserves the published Alpha.7 pair. */
2
+ export const GRAPH_PACKAGE_TARGETS = Object.freeze(['win32-x64', 'linux-x64', 'darwin-arm64', 'darwin-x64']);
3
+ export const graphArchiveName = (target) => `afyx-graph-${target}.${target.startsWith('win32-') ? 'zip' : 'tar.gz'}`;
4
+ export function graphManifestTargets(manifest) {
5
+ if (manifest?.schema === 1 || manifest?.schema === undefined) return GRAPH_PACKAGE_TARGETS.slice(0, 2);
6
+ if (manifest?.schema === 2) return [...GRAPH_PACKAGE_TARGETS];
7
+ throw new Error('Unsupported Graph release schema');
8
+ }
@@ -17,6 +17,7 @@ import { createHash } from 'node:crypto';
17
17
  import { existsSync, readFileSync, statSync } from 'node:fs';
18
18
  import { tmpdir } from 'node:os';
19
19
  import { join, resolve } from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
20
21
 
21
22
  export const AFYX_HOST_ADAPTERS_CONTRACT = 'AfyxHostAdapters/v1';
22
23
 
@@ -177,6 +178,7 @@ export function createInstalledHostAdapters({
177
178
  skillRoots = {},
178
179
  nodePath = process.execPath,
179
180
  environment = process.env,
181
+ trustedCapabilities = {},
180
182
  } = {}) {
181
183
  if (!isNonEmptyString(installRoot) || !isNonEmptyString(projectRoot)) {
182
184
  throw new TypeError('installRoot and projectRoot are required non-empty paths');
@@ -194,7 +196,29 @@ export function createInstalledHostAdapters({
194
196
  const efficientSkillDir = skillRoots['efficient-coding'] ?? join(resolvedInstallRoot, 'skills', 'efficient-coding');
195
197
  const codexToolFile = codexToolsRoot ? join(resolve(codexToolsRoot), 'CodexUsage.psm1') : null;
196
198
 
199
+ let documentationCatalog, usageAnalytics, nativeExecution, githubReader;
200
+ const success = (data, capability, evidence = []) => ({ status: 'SUCCESS', output: data, capability,
201
+ evidence, outputBytes: Buffer.byteLength(JSON.stringify(data)), followUpRequests: [] });
197
202
  return Object.freeze({
203
+
204
+ 'afyx-native-execution': async (request, { signal } = {}) => {
205
+ const { createNativeExecution } = await import('./afyx-native-execution.mjs');
206
+ nativeExecution ??= createNativeExecution({ projectRoot: resolvedProjectRoot, ...trustedCapabilities.nativeExecution, environment });
207
+ const result = await nativeExecution.execute(request.payload ?? { capabilityId: 'node-version', arguments: {} }, { signal });
208
+ return { ...success(result, 'validated-local-execution'), status: result.status === 'SUCCESS' ? 'SUCCESS' : 'FAILED', reason: result.receipt?.reason };
209
+ },
210
+ 'afyx-native-github': async (request, { signal } = {}) => {
211
+ if (!trustedCapabilities.github) return { status: 'FAILED', reason: 'GITHUB_HOST_SCOPE_REQUIRED', output: null };
212
+ const { createGitHubReader } = await import('./afyx-native-github.mjs');
213
+ githubReader ??= createGitHubReader(trustedCapabilities.github);
214
+ const result = await githubReader.read(request.payload, { signal });
215
+ return { ...success(result, 'scoped-github-evidence'), status: result.status === 'SUCCESS' ? 'SUCCESS' : 'FAILED', reason: result.code };
216
+ },
217
+ 'afyx-security-auditor': async () => {
218
+ const { auditDirectory } = await import('./afyx-security-auditor.mjs');
219
+ return success(auditDirectory(resolvedProjectRoot, trustedCapabilities.securityAudit), 'source-security-candidates');
220
+ },
221
+
198
222
  /**
199
223
  * Real host adapter for Afyx Graph
200
224
  */
@@ -276,6 +300,19 @@ export function createInstalledHostAdapters({
276
300
  * Real host adapter for Afyx Context Engine
277
301
  */
278
302
  'afyx-context': async (request) => {
303
+ if (['documentation-search', 'documentation-research', 'usage-analytics'].includes(request.taskType)) {
304
+ const contextModule = await import(pathToFileURL(join(resolvedInstallRoot, 'context', 'current', 'dist', 'index.js')).href);
305
+ if (request.taskType === 'usage-analytics') {
306
+ usageAnalytics ??= contextModule.createUsageAnalytics(trustedCapabilities.usage);
307
+ for (const event of trustedCapabilities.usage?.events ?? []) usageAnalytics.record(event);
308
+ return success(usageAnalytics.summarize(request.payload ?? {}), 'bounded-context-optimization');
309
+ }
310
+ documentationCatalog ??= contextModule.createDocumentationCatalog({ projectRoot: resolvedProjectRoot,
311
+ sources: [{ id: 'readme', path: 'README.md', domain: 'engineering' }], ...trustedCapabilities.documentation });
312
+ const result = documentationCatalog.search(request.payload ?? { query: request.task?.intent ?? request.intent });
313
+ return success(result, 'bounded-context-optimization', result.items.map((item) => ({ kind: 'documentation-source', path: item.path, sha256: item.sha256 })));
314
+ }
315
+
279
316
  // Check for explicit OFF environment variable
280
317
  if (String(environment?.AFYX_CONTEXT_OPT_IN ?? '').trim() === '0') {
281
318
  return { status: 'FAILED', reason: 'EXPLICITLY_DISABLED', output: null };
@@ -359,6 +396,13 @@ export function createInstalledHostAdapters({
359
396
  * Real host adapter for Afyx Forge Core
360
397
  */
361
398
  'afyx-forge': async (request) => {
399
+ if (['workflow-execution', 'multi-agent-workflow'].includes(request.taskType)) {
400
+ if (!trustedCapabilities.forge) return { status: 'FAILED', reason: 'FORGE_HOST_ADAPTERS_REQUIRED', output: null };
401
+ const forge = await import(pathToFileURL(join(resolvedInstallRoot, 'forge', 'current', 'src', 'index.js')).href);
402
+ const result = await forge.executeForgeWorkflow(request.payload, trustedCapabilities.forge);
403
+ return { ...success(result, 'adaptive-engineering-policy'), status: result.status === 'SUCCESS' ? 'SUCCESS' : 'FAILED' };
404
+ }
405
+
362
406
  if (!existsSync(forgeEntrypoint)) {
363
407
  return { status: 'FAILED', reason: 'FORGE_ENTRYPOINT_NOT_FOUND', output: null };
364
408
  }
@@ -453,6 +497,14 @@ export function createInstalledHostAdapters({
453
497
  * Real host adapter for Afyx Engineering Expert (Skill)
454
498
  */
455
499
  'afyx-engineering-expert': async (request) => {
500
+ if (['skill-discovery', 'skill-refinement', 'skill-composition'].includes(request.taskType)) {
501
+ const catalog = await import('./afyx-skill-catalog.mjs');
502
+ if (request.taskType === 'skill-refinement') return success(catalog.refineSkillSpecification(request.payload), 'cross-disciplinary-expertise');
503
+ if (request.taskType === 'skill-composition') return success(catalog.composeSkillSpecifications(request.payload?.skills), 'cross-disciplinary-expertise');
504
+ const result = catalog.discoverSkillDescriptors({ roots: [resolve(expertSkillDir, '..')], ...trustedCapabilities.skills });
505
+ return success(result, 'cross-disciplinary-expertise');
506
+ }
507
+
456
508
  const skillFile = join(expertSkillDir, 'SKILL.md');
457
509
  if (!existsSync(skillFile)) {
458
510
  return { status: 'FAILED', reason: 'EXPERT_SKILL_FILE_NOT_FOUND', output: null };
@@ -21,6 +21,10 @@ export const HOST_BRIDGE_FILES = Object.freeze([
21
21
  'afyx-tool-family-routing.mjs',
22
22
  'afyx-native-skill-host.mjs',
23
23
  'afyx-skill-engineering.mjs',
24
+ 'afyx-skill-catalog.mjs',
25
+ 'afyx-native-execution.mjs',
26
+ 'afyx-native-github.mjs',
27
+ 'afyx-security-auditor.mjs',
24
28
  'components.json',
25
29
  ]);
26
30
 
@@ -46,6 +46,9 @@ export async function invokeHostWorkflow({
46
46
  budgetLimits = undefined,
47
47
  environment = process.env,
48
48
  trustedSkillEngineering = null,
49
+ trustedCapabilities = {},
50
+ hostMetadata = {},
51
+ loadCapabilityDetails,
49
52
  } = {}) {
50
53
  const parsedTask = typeof task === 'string' ? JSON.parse(task) : task;
51
54
  const resolvedProjectRoot = resolve(projectRoot);
@@ -62,6 +65,9 @@ export async function invokeHostWorkflow({
62
65
  budgetLimits,
63
66
  environment,
64
67
  trustedSkillEngineering,
68
+ trustedCapabilities,
69
+ hostMetadata,
70
+ loadCapabilityDetails,
65
71
  });
66
72
 
67
73
  return {
@@ -223,12 +229,29 @@ export function serveHostMcpBridge(serverOptions = {}) {
223
229
  return rl;
224
230
  }
225
231
 
232
+ function trustedLaunchCapabilities() {
233
+ const repositories = (argumentValue('--github-repositories') || '').split(',').filter(Boolean);
234
+ if (!repositories.length) return {};
235
+ const github = { allowedRepositories: repositories };
236
+ const executable = argumentValue('--github-gh-executable');
237
+ return { github, githubExecutable: executable };
238
+ }
239
+
226
240
  function argumentValue(flag) {
227
241
  const index = process.argv.indexOf(flag);
228
242
  return index >= 0 && index + 1 < process.argv.length ? process.argv[index + 1] : null;
229
243
  }
230
244
 
231
245
  async function main() {
246
+ const trustedCapabilities = trustedLaunchCapabilities();
247
+ if (trustedCapabilities.githubExecutable) {
248
+ const { createGhRequest } = await import('./afyx-native-github.mjs');
249
+ trustedCapabilities.github.request = createGhRequest({ executable: trustedCapabilities.githubExecutable,
250
+ projectRoot: resolve(argumentValue('--project-root') || process.cwd()) });
251
+ trustedCapabilities.github.authMode = 'HOST_GH_SESSION';
252
+ delete trustedCapabilities.githubExecutable;
253
+ }
254
+
232
255
  if (process.argv.includes('--mcp') || (process.argv.includes('serve') && process.argv.includes('--mcp'))) {
233
256
  const installRoot = argumentValue('--install-root');
234
257
  const projectRoot = argumentValue('--project-root');
@@ -236,6 +259,7 @@ async function main() {
236
259
  const authorizedIds = new Set((argumentValue('--authorize') ?? '').split(',').filter(Boolean));
237
260
  const authorizations = Object.fromEntries([...authorizedIds].map((id) => [id, true]));
238
261
  serveHostMcpBridge({
262
+ trustedCapabilities,
239
263
  installRoot,
240
264
  projectRoot,
241
265
  provider,
@@ -267,6 +291,7 @@ async function main() {
267
291
 
268
292
  const authorizations = Object.fromEntries([...authorizedIds].map((id) => [id, true]));
269
293
  const result = await invokeHostWorkflow({
294
+ trustedCapabilities,
270
295
  installRoot,
271
296
  projectRoot,
272
297
  task,