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
@@ -12,8 +12,8 @@
12
12
  * Read-only by design; produces verifiable line-level evidence without mutation.
13
13
  */
14
14
 
15
- import { readFileSync, readdirSync, statSync } from 'node:fs';
16
- import { extname, join, relative, resolve } from 'node:path';
15
+ import { readFileSync, readdirSync, lstatSync, realpathSync, openSync, readSync, closeSync, fstatSync, constants } from 'node:fs';
16
+ import { extname, join, relative, resolve, isAbsolute, sep } from 'node:path';
17
17
  import { fileURLToPath } from 'node:url';
18
18
 
19
19
  export const SECURITY_AUDITOR_CONTRACT = 'afyx-security-audit-v1';
@@ -99,6 +99,7 @@ const IGNORED_DIRECTORIES = new Set([
99
99
  export function auditContent(content, filePath = 'unknown') {
100
100
  const findings = [];
101
101
  const lines = content.split(/\r?\n/);
102
+ const secretRule = AUDIT_RULES.find((rule) => rule.id === 'SEC-SECRET-01');
102
103
 
103
104
  for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
104
105
  const line = lines[lineIdx];
@@ -117,7 +118,8 @@ export function auditContent(content, filePath = 'unknown') {
117
118
  title: rule.title,
118
119
  filePath,
119
120
  lineNumber: lineIdx + 1,
120
- snippet: trimmed.slice(0, 120),
121
+ snippet: secretRule.patterns.some((pattern) => pattern.test(line)) ? '[REDACTED: sensitive source line]' : trimmed.slice(0, 120),
122
+ verification: 'HEURISTIC_CANDIDATE',
121
123
  remediation: rule.remediation,
122
124
  });
123
125
  break; // Avoid duplicate reports for same rule on same line
@@ -132,72 +134,67 @@ export function auditContent(content, filePath = 'unknown') {
132
134
  /**
133
135
  * Recursively audits a directory tree.
134
136
  */
135
- export function auditDirectory(rootDir, { failOnSeverity = null } = {}) {
136
- const resolvedRoot = resolve(rootDir);
137
- const allFindings = [];
138
- let scannedFilesCount = 0;
139
-
140
- function walk(dir) {
137
+ export function auditDirectory(rootDir, { failOnSeverity = null, maxFiles = 1000, maxDepth = 20,
138
+ maxFileBytes = 1048576, maxTotalBytes = 16777216, maxFindings = 1000, maxDurationMs = 5000 } = {}) {
139
+ for (const value of [maxFiles, maxDepth, maxFileBytes, maxTotalBytes, maxFindings, maxDurationMs]) {
140
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error('AUDIT_INVALID_LIMIT');
141
+ }
142
+ let resolvedRoot = resolve(rootDir);
143
+ // macOS /var aliases (and trusted parent aliases) resolve before containment.
144
+ // The selected root itself must still be an ordinary directory.
145
+ try { if (!lstatSync(resolvedRoot).isSymbolicLink()) resolvedRoot = realpathSync(resolvedRoot); } catch { /* reported below */ }
146
+ const findings = [], diagnostics = [], visited = new Set();
147
+ let scannedFilesCount = 0, totalBytes = 0;
148
+ const started = Date.now();
149
+ const diagnostic = (code, file = '') => { if (diagnostics.length < 100) diagnostics.push({ code, path: file }); };
150
+ const within = (file) => { const rel = relative(resolvedRoot, file); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); };
151
+ function walk(dir, depth = 0) {
152
+ if (Date.now() - started >= maxDurationMs || depth > maxDepth) { diagnostic('SCAN_LIMIT'); return; }
141
153
  let entries;
142
- try {
143
- entries = readdirSync(dir);
144
- } catch {
145
- return;
146
- }
147
-
148
- for (const entry of entries) {
149
- if (IGNORED_DIRECTORIES.has(entry)) continue;
150
- const fullPath = join(dir, entry);
151
- let st;
154
+ try { const real = realpathSync(dir); if (!within(real) || visited.has(real)) { diagnostic('PATH_BOUNDARY'); return; }
155
+ visited.add(real); entries = readdirSync(dir).sort(); }
156
+ catch { diagnostic('UNREADABLE_DIRECTORY', relative(resolvedRoot, dir)); return; }
157
+ for (const name of entries) {
158
+ if (IGNORED_DIRECTORIES.has(name)) continue;
159
+ if (scannedFilesCount >= maxFiles || totalBytes >= maxTotalBytes || findings.length >= maxFindings || Date.now() - started >= maxDurationMs) { diagnostic('SCAN_LIMIT'); break; }
160
+ const full = join(dir, name), rel = relative(resolvedRoot, full);
161
+ let stat;
162
+ try { stat = lstatSync(full); } catch { diagnostic('UNREADABLE_ENTRY', rel); continue; }
163
+ if (stat.isSymbolicLink()) { diagnostic('SYMLINK_SKIPPED', rel); continue; }
164
+ if (stat.isDirectory()) { walk(full, depth + 1); continue; }
165
+ if (!stat.isFile() || !SCANNABLE_EXTENSIONS.has(extname(name).toLowerCase())) continue;
166
+ if (stat.nlink > 1 || stat.size > maxFileBytes || totalBytes + stat.size > maxTotalBytes) { diagnostic('FILE_LIMIT', rel); continue; }
167
+ let fd;
152
168
  try {
153
- st = statSync(fullPath);
154
- } catch {
155
- continue;
156
- }
157
-
158
- if (st.isDirectory()) {
159
- walk(fullPath);
160
- } else if (st.isFile()) {
161
- const ext = extname(entry).toLowerCase();
162
- if (SCANNABLE_EXTENSIONS.has(ext)) {
163
- scannedFilesCount++;
164
- try {
165
- const content = readFileSync(fullPath, 'utf8');
166
- const relPath = relative(resolvedRoot, fullPath).replace(/\\/g, '/');
167
- const fileFindings = auditContent(content, relPath);
168
- allFindings.push(...fileFindings);
169
- } catch {
170
- // Unreadable file skipped cleanly
171
- }
172
- }
173
- }
169
+ if (!within(realpathSync(full))) { diagnostic('PATH_BOUNDARY', rel); continue; }
170
+ fd = openSync(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));
171
+ const opened = fstatSync(fd);
172
+ if (!opened.isFile() || opened.nlink > 1 || opened.ino !== stat.ino || opened.dev !== stat.dev) { diagnostic('FILE_CHANGED', rel); continue; }
173
+ const bytes = Buffer.alloc(Math.min(maxFileBytes, stat.size) + 1);
174
+ const count = readSync(fd, bytes, 0, bytes.length, 0);
175
+ if (count > stat.size || count > maxFileBytes) { diagnostic('FILE_CHANGED', rel); continue; }
176
+ totalBytes += count; scannedFilesCount++;
177
+ const found = auditContent(bytes.subarray(0, count).toString('utf8'), rel);
178
+ const available = maxFindings - findings.length;
179
+ findings.push(...found.slice(0, available));
180
+ if (found.length > available) diagnostic('FINDING_LIMIT', rel);
181
+ } catch { diagnostic('UNREADABLE_FILE', rel); }
182
+ finally { if (fd !== undefined) closeSync(fd); }
174
183
  }
175
184
  }
176
-
177
- walk(resolvedRoot);
178
-
179
- const summary = {
180
- critical: allFindings.filter((f) => f.severity === RISK_LEVELS.CRITICAL).length,
181
- high: allFindings.filter((f) => f.severity === RISK_LEVELS.HIGH).length,
182
- medium: allFindings.filter((f) => f.severity === RISK_LEVELS.MEDIUM).length,
183
- low: allFindings.filter((f) => f.severity === RISK_LEVELS.LOW).length,
184
- };
185
-
186
- const hasFailingFindings = failOnSeverity === 'HIGH'
187
- ? summary.critical > 0 || summary.high > 0
188
- : summary.critical > 0;
189
-
190
- return {
191
- contract: SECURITY_AUDITOR_CONTRACT,
192
- targetRoot: resolvedRoot,
193
- scannedFilesCount,
194
- status: allFindings.length === 0 ? 'PASS' : hasFailingFindings ? 'FAIL' : 'WARNING',
195
- summary,
196
- findings: allFindings,
197
- };
185
+ try {
186
+ if (lstatSync(resolvedRoot).isSymbolicLink() || realpathSync(resolvedRoot) !== resolvedRoot) diagnostic('UNSAFE_ROOT');
187
+ else if (!lstatSync(resolvedRoot).isDirectory()) diagnostic('INVALID_ROOT');
188
+ else walk(resolvedRoot);
189
+ } catch { diagnostic('UNREADABLE_ROOT'); }
190
+ const summary = Object.fromEntries(Object.entries(RISK_LEVELS).map(([key, level]) => [key.toLowerCase(), findings.filter((f) => f.severity === level).length]));
191
+ const failing = failOnSeverity === 'HIGH' ? summary.critical + summary.high > 0 : summary.critical > 0;
192
+ return { contract: SECURITY_AUDITOR_CONTRACT, targetRoot: resolvedRoot, scannedFilesCount, totalBytes,
193
+ status: failing ? 'FAIL' : diagnostics.length ? 'INCOMPLETE' : findings.length ? 'WARNING' : 'PASS',
194
+ summary, findings, diagnostics, coverage: diagnostics.length ? 'PARTIAL' : 'COMPLETE_WITHIN_RULES',
195
+ verification: 'HEURISTIC_CANDIDATES_NOT_CONFIRMED_VULNERABILITIES' };
198
196
  }
199
197
 
200
- // CLI entry point
201
198
  if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
202
199
  const target = process.argv[2] || process.cwd();
203
200
  const isJson = process.argv.includes('--json');
@@ -220,5 +217,5 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur
220
217
  }
221
218
  }
222
219
 
223
- if (report.status === 'FAIL') process.exit(1);
220
+ if (report.status === 'FAIL' || report.status === 'INCOMPLETE') process.exit(1);
224
221
  }
@@ -0,0 +1,83 @@
1
+ /** AFYX lazy skill descriptors. Discovery reads metadata, never executes skill instructions. */
2
+ import { createHash } from 'node:crypto';
3
+ import { lstatSync, realpathSync, readdirSync, readFileSync } from 'node:fs';
4
+ import { join, resolve, relative, isAbsolute, sep } from 'node:path';
5
+
6
+ export const SKILL_CATALOG_CONTRACT = 'AfyxSkillCatalog/v1';
7
+ const hash = (x) => createHash('sha256').update(x).digest('hex');
8
+ const within = (root, file) => { const p = relative(root, file); return p !== '..' && !p.startsWith(`..${sep}`) && !isAbsolute(p); };
9
+ const allowed = (root, file) => {
10
+ let current = root;
11
+ if (lstatSync(root).isSymbolicLink()) throw new Error('UNSAFE_SKILL_ROOT');
12
+ for (const part of relative(root, file).split(sep).filter(Boolean)) { current = join(current, part); if (lstatSync(current).isSymbolicLink()) throw new Error('UNSAFE_SKILL_PATH'); }
13
+ if (!within(realpathSync(root), realpathSync(file))) throw new Error('UNSAFE_SKILL_PATH');
14
+ };
15
+
16
+ export function discoverSkillDescriptors({ roots = [], provider = 'codex', scope = 'workspace', maxSkills = 64, maxManifestBytes = 32768 } = {}) {
17
+ if (!Array.isArray(roots) || roots.length > 16 || !['codex', 'antigravity', 'claude'].includes(provider) || !['workspace', 'global'].includes(scope)
18
+ || !Number.isSafeInteger(maxSkills) || maxSkills < 1 || maxSkills > 256 || !Number.isSafeInteger(maxManifestBytes) || maxManifestBytes < 1 || maxManifestBytes > 131072) throw new Error('INVALID_CATALOG_CONFIG');
19
+ const items = [], diagnostics = [];
20
+ for (const input of roots) {
21
+ const root = resolve(input);
22
+ try {
23
+ allowed(root, root);
24
+ for (const name of readdirSync(root).sort()) {
25
+ if (items.length >= maxSkills) { diagnostics.push({ code: 'SKILL_LIMIT' }); break; }
26
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) continue;
27
+ const directory = join(root, name), manifest = join(directory, 'SKILL.md');
28
+ try {
29
+ allowed(root, manifest); const stat = lstatSync(manifest);
30
+ if (!stat.isFile() || stat.nlink > 1 || stat.size > maxManifestBytes) throw new Error('MANIFEST_LIMIT');
31
+ const bytes = readFileSync(manifest); if (bytes.length > maxManifestBytes) throw new Error('MANIFEST_LIMIT');
32
+ const text = bytes.toString('utf8'), front = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
33
+ if (!front || /[!&*][A-Za-z_][\w-]*|!!|<<:/.test(front)) throw new Error('UNSUPPORTED_METADATA');
34
+ const field = (key) => front.match(new RegExp(`^${key}:\\s*([^\\r\\n]*)`, 'm'))?.[1]?.trim().replace(/^['"]|['"]$/g, '') || '';
35
+ const declared = field('name'); if (declared !== name) throw new Error('MANIFEST_NAME_MISMATCH');
36
+ let description = field('description');
37
+ if (/^[>|][-+]?$/.test(description)) description = front.match(/^description:\s*[>|][-+]?\r?\n((?:[ \t]+[^\r\n]*(?:\r?\n|$))+)/m)?.[1]?.replace(/\r?\n\s*/g, ' ').trim() || '';
38
+ const version = front.match(/^\s+version:\s*["']?([^\s"']+)/m)?.[1] || front.match(/"version"\s*:\s*"([^"]+)"/)?.[1] || field('version') || 'UNKNOWN';
39
+ if (!description || description.length > 4096) throw new Error('UNSUPPORTED_METADATA');
40
+ items.push(Object.freeze({ id: name, name, description, version, root: directory, manifest, providerScope: `${provider}:${scope}`,
41
+ domains: name.includes('odoo') ? ['odoo', 'python', 'erp'] : name.includes('expert') ? ['engineering', 'architecture', 'security'] : ['coding'],
42
+ manifestSha256: hash(bytes), manifestBytes: bytes.length, status: 'DISCOVERED_NOT_EXECUTED' }));
43
+ } catch (error) { if (error.code !== 'ENOENT') diagnostics.push({ id: name, code: ['UNSAFE_SKILL_PATH', 'MANIFEST_LIMIT', 'UNSUPPORTED_METADATA', 'MANIFEST_NAME_MISMATCH'].includes(error.message) ? error.message : 'SKILL_UNAVAILABLE' }); }
44
+ }
45
+ } catch { diagnostics.push({ code: 'SKILL_ROOT_UNAVAILABLE' }); }
46
+ }
47
+ const grouped = new Map();
48
+ for (const item of items) { if (grouped.has(item.id)) diagnostics.push({ id: item.id, code: 'DUPLICATE_SKILL_ID' }); else grouped.set(item.id, item); }
49
+ return Object.freeze({ contract: SKILL_CATALOG_CONTRACT, items: Object.freeze([...grouped.values()]), diagnostics: Object.freeze(diagnostics) });
50
+ }
51
+
52
+ export function loadSkillContext(descriptor, { authorize, maxBytes = 32768 } = {}) {
53
+ if (!descriptor || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || typeof authorize !== 'function' || authorize(descriptor) !== true) throw new Error('SKILL_HOST_AUTHORIZATION_REQUIRED');
54
+ allowed(descriptor.root, descriptor.manifest);
55
+ if (lstatSync(descriptor.manifest).size > maxBytes) throw new Error('SKILL_CONTEXT_LIMIT');
56
+ const bytes = readFileSync(descriptor.manifest);
57
+ if (bytes.length > maxBytes || hash(bytes) !== descriptor.manifestSha256) throw new Error('SKILL_SOURCE_CHANGED');
58
+ return { contract: SKILL_CATALOG_CONTRACT, id: descriptor.id, sourceDigest: descriptor.manifestSha256, content: bytes.toString('utf8'),
59
+ bytes: bytes.length, disposition: 'INSTRUCTIONS_SUBORDINATE_TO_HOST_POLICY', executionPerformed: false };
60
+ }
61
+
62
+ export function refineSkillSpecification(spec = {}) {
63
+ const diagnostics = [];
64
+ const text = (key, max) => { const value = spec[key]; if (typeof value !== 'string' || !value.trim() || value.length > max) { diagnostics.push({ field: key, code: 'REQUIRED_BOUNDED_TEXT' }); return ''; } return value.trim(); };
65
+ const list = (key) => { if (!Array.isArray(spec[key]) || spec[key].length > 32 || spec[key].some((x) => typeof x !== 'string' || !x.trim() || x.length > 512)) { diagnostics.push({ field: key, code: 'REQUIRED_BOUNDED_LIST' }); return []; } return [...new Set(spec[key].map((x) => x.trim()))]; };
66
+ const normalized = { name: text('name', 64), objective: text('objective', 4096), domain: text('domain', 64), inputs: list('inputs'), outputs: list('outputs'), acceptance: list('acceptance'), permissions: list('permissions') };
67
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(normalized.name)) diagnostics.push({ field: 'name', code: 'INVALID_NAME' });
68
+ if (!normalized.acceptance.length) diagnostics.push({ field: 'acceptance', code: 'ACCEPTANCE_REQUIRED' });
69
+ return { contract: 'AfyxSkillSpecification/v1', status: diagnostics.length ? 'INVALID' : 'VALID', specification: normalized, diagnostics, executionOwner: 'afyx-forge', contextOwner: 'afyx-context' };
70
+ }
71
+
72
+ export function composeSkillSpecifications(specs = []) {
73
+ if (!Array.isArray(specs) || specs.length > 16) throw new Error('SKILL_COMPOSITION_LIMIT');
74
+ const items = specs.map(refineSkillSpecification), conflicts = [], names = new Set(), domains = new Map();
75
+ for (const item of items) {
76
+ const spec = item.specification;
77
+ if (item.status !== 'VALID') conflicts.push({ name: spec.name, code: 'INVALID_SPECIFICATION' });
78
+ if (names.has(spec.name)) conflicts.push({ name: spec.name, code: 'DUPLICATE_NAME' }); names.add(spec.name);
79
+ if (domains.has(spec.domain)) conflicts.push({ domain: spec.domain, code: 'DOMAIN_OWNER_CONFLICT', owners: [domains.get(spec.domain), spec.name] });
80
+ else domains.set(spec.domain, spec.name);
81
+ }
82
+ return { contract: 'AfyxSkillComposition/v1', status: conflicts.length ? 'CONFLICT' : 'COMPOSABLE', items, conflicts, executionPerformed: false, executionOwner: 'afyx-forge' };
83
+ }
@@ -352,3 +352,5 @@ export function rollbackSkillInstall({ provider, skillsRoot, name }, { authorize
352
352
  catch (error) { renameSync(displaced, target); throw error; }
353
353
  return { status: 'ROLLED_BACK', target, digest: previous.digest, displaced };
354
354
  }
355
+
356
+ export { discoverSkillDescriptors, loadSkillContext, refineSkillSpecification, composeSkillSpecifications } from './afyx-skill-catalog.mjs';
@@ -3,6 +3,7 @@
3
3
  /** Native installed-component discovery and execution for AfyxUniversalInterop/v1. */
4
4
 
5
5
  import { createHash } from 'node:crypto';
6
+ import { performance } from 'node:perf_hooks';
6
7
  import { spawnSync } from 'node:child_process';
7
8
  import {
8
9
  existsSync,
@@ -23,10 +24,12 @@ import { fileURLToPath } from 'node:url';
23
24
 
24
25
  import {
25
26
  classifyTaskIntent,
27
+ DEFAULT_BUDGET_LIMITS,
26
28
  executeAfyxCapabilityRoute,
27
29
  } from './afyx-capability-orchestrator.mjs';
28
30
  import { createInstalledHostAdapters } from './afyx-host-adapters.mjs';
29
31
  import { createNativeSkillHostAdapter } from './afyx-native-skill-host.mjs';
32
+ import { ACCEPTED_PROVIDERS } from './afyx-modular-runtime.mjs';
30
33
 
31
34
  export const AFYX_UNIVERSAL_RUNTIME_CONTRACT = 'AfyxUniversalRuntime/v1';
32
35
  export const AFYX_COMPONENT_MANIFEST_CONTRACT = 'AfyxComponentManifest/v1';
@@ -110,11 +113,11 @@ function componentEnabled(componentId, settings, environment) {
110
113
  return true;
111
114
  }
112
115
 
113
- function inspectGraphIndex(projectRoot, entrypoint, nodePath, environment) {
116
+ function inspectGraphIndex(projectRoot, entrypoint, nodePath, environment, timeoutMs = 10_000) {
114
117
  // Graph's status command is the authority for ancestor resolution, ownership,
115
118
  // extraction compatibility, pending changes and incomplete indexes.
116
119
  const result = spawnSync(nodePath, [entrypoint, 'status', projectRoot, '--json'], {
117
- encoding: 'utf8', windowsHide: true, timeout: 10_000,
120
+ encoding: 'utf8', windowsHide: true, timeout: timeoutMs,
118
121
  maxBuffer: 2 * 1024 * 1024, env: environment,
119
122
  });
120
123
  if (result.status !== 0 || result.error) return { indexReady: false, indexFresh: false };
@@ -194,6 +197,9 @@ function inspectKnownComponents({
194
197
  authorizations,
195
198
  environment,
196
199
  componentStateOverrides,
200
+ probeGraph = true,
201
+ preparationEvents = [],
202
+ probeTimeoutMs = 10_000,
197
203
  }) {
198
204
  const states = {};
199
205
  const evidence = [];
@@ -214,10 +220,13 @@ function inspectKnownComponents({
214
220
  componentSettings?.[componentId],
215
221
  environment,
216
222
  );
217
- const graph = componentId === 'afyx-graph' && installed
218
- ? inspectGraphIndex(projectRoot, join(root, 'current', 'lib', 'dist', 'bin', 'afyx-graph.js'), nodePath, environment)
219
- : (componentId === 'afyx-graph' ? { indexReady: false, indexFresh: false } : {});
220
223
  const override = componentStateOverrides?.[componentId] ?? {};
224
+ const inspectGraph = componentId === 'afyx-graph' && installed && enabled && sourceIdentity !== null &&
225
+ override.healthy !== false && override.compatible !== false && authorizations?.[componentId] === true && probeGraph;
226
+ if (inspectGraph) preparationEvents.push('afyx-graph/status');
227
+ const graph = inspectGraph
228
+ ? inspectGraphIndex(projectRoot, join(root, 'current', 'lib', 'dist', 'bin', 'afyx-graph.js'), nodePath, environment, probeTimeoutMs)
229
+ : (componentId === 'afyx-graph' ? { indexReady: false, indexFresh: false } : {});
221
230
  states[componentId] = {
222
231
  installed,
223
232
  enabled,
@@ -281,6 +290,10 @@ function discoverDynamicComponents({
281
290
  }) {
282
291
  const componentsRoot = join(installRoot, 'components');
283
292
  const states = {};
293
+ const bundledStates = Object.fromEntries(['afyx-native-execution', 'afyx-native-github', 'afyx-security-auditor'].map((id) => [id, {
294
+ installed: true, enabled: componentEnabled(id, componentSettings?.[id], environment), healthy: true, compatible: true,
295
+ authorized: authorizations[id] === true, sourceIdentity: sha256File(fileURLToPath(new URL(`./${id}.mjs`, import.meta.url))), observationSource: 'BUNDLED_HOST_CAPABILITY',
296
+ }]));
284
297
  const adapters = {};
285
298
  const evidence = [];
286
299
  if (!existsSync(componentsRoot) || !statSync(componentsRoot).isDirectory()) {
@@ -361,6 +374,11 @@ export function createInstalledAfyxRuntime({
361
374
  environment = process.env,
362
375
  nodePath = process.execPath,
363
376
  trustedSkillEngineering = null,
377
+ trustedCapabilities = {},
378
+ probeGraph = true,
379
+ providerPermissions = {},
380
+ hostAuthorizations = {},
381
+ probeTimeoutMs = 10_000,
364
382
  } = {}) {
365
383
  if (typeof installRoot !== 'string' || !installRoot.trim() ||
366
384
  typeof projectRoot !== 'string' || !projectRoot.trim()) {
@@ -368,6 +386,12 @@ export function createInstalledAfyxRuntime({
368
386
  }
369
387
  const resolvedInstallRoot = resolve(installRoot);
370
388
  const resolvedProjectRoot = resolve(projectRoot);
389
+ const preparationEvents = [];
390
+ const graphProbeAuthorized = (provider === null || ACCEPTED_PROVIDERS.includes(provider)) &&
391
+ providerPermissions['afyx-graph'] !== false && providerPermissions['repository-graph-evidence'] !== false &&
392
+ hostAuthorizations[provider] !== false && hostAuthorizations.providers?.[provider] !== false &&
393
+ hostAuthorizations.enabledProviders?.[provider] !== false &&
394
+ (hostAuthorizations.mcpEnabled !== false || hostAuthorizations.cliBypassAllowed === true);
371
395
  // Usage Tracking is a Codex/Windows toolset installed under the provider's
372
396
  // tools root, outside the shared AFYX runtime directory.
373
397
  const resolvedToolsRoot = provider === 'codex' && process.platform === 'win32'
@@ -383,6 +407,9 @@ export function createInstalledAfyxRuntime({
383
407
  authorizations,
384
408
  environment,
385
409
  componentStateOverrides,
410
+ probeGraph: probeGraph && graphProbeAuthorized,
411
+ preparationEvents,
412
+ probeTimeoutMs,
386
413
  });
387
414
  const dynamic = discoverDynamicComponents({
388
415
  installRoot: resolvedInstallRoot,
@@ -407,8 +434,11 @@ export function createInstalledAfyxRuntime({
407
434
  sourceIdentity: nativeSkill.sourceIdentity,
408
435
  observationSource: 'TRUSTED_HOST_ADAPTER',
409
436
  } : null;
410
- const adapters = {
411
- ...createInstalledHostAdapters({
437
+ const bundledStates = Object.fromEntries(['afyx-native-execution', 'afyx-native-github', 'afyx-security-auditor'].map((id) => [id, {
438
+ installed: true, enabled: componentEnabled(id, componentSettings?.[id], environment), healthy: true, compatible: true,
439
+ authorized: authorizations[id] === true, sourceIdentity: sha256File(fileURLToPath(new URL(`./${id}.mjs`, import.meta.url))), observationSource: 'BUNDLED_HOST_CAPABILITY',
440
+ }]));
441
+ const adapterOptions = {
412
442
  installRoot: resolvedInstallRoot,
413
443
  projectRoot: resolvedProjectRoot,
414
444
  graphIndexRoot: known.states['afyx-graph']?.indexRoot ?? null,
@@ -419,7 +449,13 @@ export function createInstalledAfyxRuntime({
419
449
  codexToolsRoot: resolvedToolsRoot,
420
450
  nodePath,
421
451
  environment,
422
- }),
452
+ trustedCapabilities,
453
+ };
454
+ const hostAdapters = createInstalledHostAdapters(adapterOptions);
455
+ let graphAdapter = hostAdapters['afyx-graph'];
456
+ const adapters = {
457
+ ...hostAdapters,
458
+ 'afyx-graph': (...args) => graphAdapter(...args),
423
459
  ...dynamic.adapters,
424
460
  ...(nativeSkill ? { 'afyx-skill-engineering': nativeSkill.adapter } : {}),
425
461
  };
@@ -429,7 +465,19 @@ export function createInstalledAfyxRuntime({
429
465
  projectRoot: resolvedProjectRoot,
430
466
  provider,
431
467
  providerSkillRoots,
432
- componentStates: Object.freeze({ ...known.states, ...dynamic.states,
468
+ get preparationEvents() { return Object.freeze([...preparationEvents]); },
469
+ prepareCapabilityState(componentId, controls = {}) {
470
+ const original = known.states[componentId];
471
+ if (componentId !== 'afyx-graph' || !graphProbeAuthorized || !original?.installed || !original.enabled || !original.authorized) return original;
472
+ const root = known.evidence.find((item) => item.componentId === componentId).root;
473
+ preparationEvents.push('afyx-graph/status');
474
+ const observed = inspectGraphIndex(resolvedProjectRoot, join(root, 'current/lib/dist/bin/afyx-graph.js'), nodePath, environment,
475
+ Math.max(1, Math.min(10_000, controls.maxExecutionMs || 10_000)));
476
+ const override = componentStateOverrides[componentId] || {};
477
+ if (observed.indexRoot) graphAdapter = createInstalledHostAdapters({ ...adapterOptions, graphIndexRoot: observed.indexRoot })['afyx-graph'];
478
+ return { ...original, ...observed, indexReady: override.indexReady ?? observed.indexReady, indexFresh: override.indexFresh ?? observed.indexFresh };
479
+ },
480
+ componentStates: Object.freeze({ ...known.states, ...dynamic.states, ...bundledStates,
433
481
  ...(nativeSkillState ? { 'afyx-skill-engineering': nativeSkillState } : {}) }),
434
482
  adapters: Object.freeze(adapters),
435
483
  discoveryEvidence: Object.freeze([...known.evidence, ...dynamic.evidence,
@@ -442,6 +490,7 @@ export function createInstalledAfyxRuntime({
442
490
 
443
491
  /** Discover, select, and execute only the capabilities justified by one task. */
444
492
  export async function runInstalledAfyxWorkflow(options = {}) {
493
+ const startedAt = performance.now();
445
494
  const task = options.task ?? {};
446
495
  const routeOptions = {
447
496
  task,
@@ -451,21 +500,34 @@ export async function runInstalledAfyxWorkflow(options = {}) {
451
500
  userPreferences: options.userPreferences ?? {},
452
501
  budgetLimits: options.budgetLimits,
453
502
  environment: options.environment ?? process.env,
503
+ hostMetadata: options.hostMetadata,
504
+ loadCapabilityDetails: options.loadCapabilityDetails,
454
505
  };
455
- if (classifyTaskIntent(task).directSource) {
506
+ if (classifyTaskIntent(task, options.hostMetadata).directSource) {
456
507
  return executeAfyxCapabilityRoute({
457
508
  ...routeOptions,
458
509
  componentStates: {},
459
510
  adapters: {},
460
511
  });
461
512
  }
462
- const runtime = createInstalledAfyxRuntime(options);
513
+ const classification = classifyTaskIntent(task, options.hostMetadata);
514
+ const exclusive = classification.odoo || classification.forgeAdvice || classification.documentation || classification.usageAnalytics ||
515
+ classification.github || classification.nativeExecution || classification.securityAudit || classification.unknownDomain || classification.ambiguousDomain;
516
+ const runtime = createInstalledAfyxRuntime({ ...options, probeTimeoutMs: Math.max(1, Math.min(10_000, options.budgetLimits?.maxExecutionMs || DEFAULT_BUDGET_LIMITS.maxExecutionMs)),
517
+ probeGraph: options.budgetLimits?.maxToolCalls !== 0 && options.budgetLimits?.maxCapabilities !== 0 &&
518
+ (classification.relational && (!exclusive || task.needsRelationalEvidence === true) ||
519
+ classification.manualSelection.includes('afyx-graph') || classification.customComponentId === 'afyx-graph' ||
520
+ classification.customCapability === 'repository-graph-evidence') });
463
521
  try {
464
- return await executeAfyxCapabilityRoute({
522
+ const result = await executeAfyxCapabilityRoute({
465
523
  ...routeOptions,
466
524
  componentStates: runtime.componentStates,
467
525
  adapters: runtime.adapters,
526
+ prepareCapabilityState: runtime.prepareCapabilityState,
527
+ preparationElapsedMs: performance.now() - startedAt,
468
528
  });
529
+ return { ...result, metrics: { ...result.metrics, runtimeDiscoveryToolCalls: runtime.preparationEvents.length,
530
+ runtimeDiscoveryInvocations: [...runtime.preparationEvents] } };
469
531
  } finally {
470
532
  runtime.dispose();
471
533
  }
@@ -251,10 +251,10 @@ case "$(uname -m)" in
251
251
  *) printf 'Unsupported architecture: %s\n' "$(uname -m)" >&2; exit 1 ;;
252
252
  esac
253
253
  target="$os-$arch"
254
- if [[ "$target" != linux-x64 ]]; then
255
- printf 'Afyx Graph prebuilt runtime is unavailable for %s. Minimal and Recommended Kit presets remain available; consumer source compilation is disabled.\n' "$target" >&2
256
- exit 2
257
- fi
254
+ case "$target" in
255
+ linux-x64|darwin-arm64|darwin-x64) ;;
256
+ *) printf 'Afyx Graph prebuilt runtime is unavailable for %s.\n' "$target" >&2; exit 2 ;;
257
+ esac
258
258
  asset="afyx-graph-$target.tar.gz"
259
259
 
260
260
  require_host_runtime
@@ -0,0 +1,11 @@
1
+ Set-StrictMode -Version Latest
2
+ function Write-AfyxInstallerProgress {
3
+ param([string]$OperationId, [string]$ComponentId = '', [string]$Phase, [string]$State, [string]$Message)
4
+ if ($env:AFYX_INSTALL_PROGRESS -ne '1') { return }
5
+ $event = [ordered]@{ contract = 'AfyxInstallerProgress/v1'; operationId = $OperationId
6
+ componentId = $(if ($ComponentId) { $ComponentId } else { $null }); phase = $Phase; state = $State
7
+ completed = $(if ($State -eq 'completed') { 1 } else { $null }); total = $(if ($State -eq 'completed') { 1 } else { $null }); message = $Message
8
+ timestamp = [DateTime]::UtcNow.ToString('o'); errorCode = $(if ($State -eq 'failed') { 'BACKEND_OPERATION_FAILED' } else { $null }) }
9
+ [Console]::Out.WriteLine('AFYX_PROGRESS ' + (ConvertTo-Json -InputObject $event -Depth 3 -Compress))
10
+ }
11
+ Export-ModuleMember -Function Write-AfyxInstallerProgress
@@ -40,15 +40,47 @@ function Restore-AfyxInterruptedSkillTransaction {
40
40
 
41
41
  function Get-AfyxSkillDigest {
42
42
  [CmdletBinding()]
43
- param([Parameter(Mandatory)][string]$Directory)
43
+ param([Parameter(Mandatory)][string]$Directory, [switch]$LegacyNls)
44
44
  $root = [IO.Path]::GetFullPath($Directory).TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar)
45
45
  $lines = @()
46
46
  $files = @(Get-ChildItem -LiteralPath $root -File -Recurse -Force | Where-Object {
47
47
  $_.Name -ne $script:MarkerName -and $_.FullName -notmatch '[\\/]\.git[\\/]'
48
- } | Sort-Object FullName)
49
- foreach ($file in $files) {
50
- $relative = $file.FullName.Substring($root.Length).TrimStart('\', '/').Replace('\', '/')
51
- $lines += "$(Get-FileHash -Algorithm SHA256 -LiteralPath $file.FullName | Select-Object -ExpandProperty Hash) ./$relative"
48
+ })
49
+ [string[]]$paths = @($files | ForEach-Object { $_.FullName })
50
+ # Culture sorting differs between .NET Framework/NLS and .NET/ICU. New
51
+ # ownership digests use one stable order on both PowerShell generations.
52
+ $comparer = [StringComparer]::OrdinalIgnoreCase
53
+ if ($LegacyNls) {
54
+ if ($env:OS -ne 'Windows_NT') { throw 'Legacy NLS skill digests require Windows.' }
55
+ if (-not ('Afyx.LegacySkillPathComparer' -as [type])) {
56
+ Add-Type -TypeDefinition @'
57
+ using System;
58
+ using System.Collections.Generic;
59
+ using System.ComponentModel;
60
+ using System.Runtime.InteropServices;
61
+ namespace Afyx {
62
+ public sealed class LegacySkillPathComparer : IComparer<string>, System.Collections.IComparer {
63
+ private readonly string locale;
64
+ public LegacySkillPathComparer(string locale) { this.locale = locale; }
65
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
66
+ private static extern int CompareStringEx(string locale, uint flags, string left, int leftLength,
67
+ string right, int rightLength, IntPtr version, IntPtr reserved, IntPtr parameter);
68
+ public int Compare(string left, string right) {
69
+ int result = CompareStringEx(locale, 1, left, -1, right, -1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
70
+ if (result == 0) throw new Win32Exception(Marshal.GetLastWin32Error());
71
+ return result - 2;
72
+ }
73
+ int System.Collections.IComparer.Compare(object left, object right) { return Compare((string)left, (string)right); }
74
+ }
75
+ }
76
+ '@
77
+ }
78
+ $comparer = New-Object Afyx.LegacySkillPathComparer ([Globalization.CultureInfo]::CurrentCulture.Name)
79
+ }
80
+ [Array]::Sort($paths, $comparer)
81
+ foreach ($file in $paths) {
82
+ $relative = $file.Substring($root.Length).TrimStart('\', '/').Replace('\', '/')
83
+ $lines += "$(Get-FileHash -Algorithm SHA256 -LiteralPath $file | Select-Object -ExpandProperty Hash) ./$relative"
52
84
  }
53
85
  $bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "`n") + "`n")
54
86
  $sha = [Security.Cryptography.SHA256]::Create()
@@ -100,6 +132,9 @@ function Get-AfyxSkillOwnership {
100
132
  if ($ExpectedOwner -eq 'afyx') {
101
133
  if ([string]$marker.content_sha256 -notmatch '^[0-9a-f]{64}$') { return 'FOREIGN_UNPROVEN' }
102
134
  if ((Get-AfyxSkillDigest -Directory $Target) -eq $marker.content_sha256) { return 'AFYX_OWNED_UNMODIFIED' }
135
+ # Legacy Windows PowerShell markers remain valid only when the
136
+ # complete current file set exactly reproduces their NLS digest.
137
+ if ($env:OS -eq 'Windows_NT' -and (Get-AfyxSkillDigest -Directory $Target -LegacyNls) -eq $marker.content_sha256) { return 'AFYX_OWNED_UNMODIFIED' }
103
138
  return 'AFYX_OWNED_MODIFIED'
104
139
  }
105
140
  if (-not (Test-Path -LiteralPath (Join-Path $Target '.git'))) { return 'FOREIGN_UNPROVEN' }
@@ -127,7 +162,8 @@ function Get-AfyxLegacySkillProvenance {
127
162
  if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { return 'UNKNOWN' }
128
163
  if ($Owner -eq 'afyx') {
129
164
  if ($LegacyContentSha256 -notmatch '^[0-9a-f]{64}$') { return 'UNKNOWN' }
130
- if ((Get-AfyxSkillDigest -Directory $Target) -eq $LegacyContentSha256) { return 'MATCH' }
165
+ if ((Get-AfyxSkillDigest -Directory $Target) -eq $LegacyContentSha256 -or
166
+ ($env:OS -eq 'Windows_NT' -and (Get-AfyxSkillDigest -Directory $Target -LegacyNls) -eq $LegacyContentSha256)) { return 'MATCH' }
131
167
  $manifest = Join-Path $Target 'SKILL.md'
132
168
  if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { return 'UNKNOWN' }
133
169
  $content = Get-Content -Raw -LiteralPath $manifest -Encoding utf8
@@ -0,0 +1,30 @@
1
+ # Native Bash 3.2 adapter for the shared installer progress protocol.
2
+ if [[ "${AFYX_INSTALL_PROGRESS:-0}" == 1 ]]; then exec 3>&1; fi
3
+ afyx_progress_escape() {
4
+ local text="$1"
5
+ text="${text//\\/\\\\}"; text="${text//\"/\\\"}"
6
+ text="${text//$'\n'/\\n}"; text="${text//$'\r'/\\r}"; text="${text//$'\t'/\\t}"
7
+ printf '%s' "$text"
8
+ }
9
+ afyx_progress_event() {
10
+ [[ "${AFYX_INSTALL_PROGRESS:-0}" == 1 ]] || return 0
11
+ local operation="$1" component="$2" phase="$3" state="$4" message="$5" encoded_component=null error=null completed=null total=null
12
+ [[ -z "$component" ]] || encoded_component="\"$(afyx_progress_escape "$component")\""
13
+ [[ "$state" != failed ]] || error='"BACKEND_OPERATION_FAILED"'
14
+ if [[ "$state" == completed ]]; then completed=1; total=1; fi
15
+ printf 'AFYX_PROGRESS {"contract":"AfyxInstallerProgress/v1","operationId":"%s","componentId":%s,"phase":"%s","state":"%s","completed":%s,"total":%s,"message":"%s","timestamp":"%s","errorCode":%s}\n' \
16
+ "$operation" "$encoded_component" "$phase" "$state" "$completed" "$total" "$(afyx_progress_escape "$message")" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$error" >&3
17
+ }
18
+ afyx_run_install_operation() {
19
+ local component="$1" phase="$2" message="$3" operation="native:$RANDOM:$RANDOM" status
20
+ shift 3
21
+ case "$phase" in install|update|repair|configure|verify|cleanup|rollback) ;; *) phase=install ;; esac
22
+ afyx_progress_event "$operation" "$component" "$phase" running "$message"
23
+ if "$@"; then
24
+ afyx_progress_event "$operation" "$component" "$phase" completed "$message"
25
+ else
26
+ status=$?
27
+ afyx_progress_event "$operation" "$component" "$phase" failed "$message"
28
+ return "$status"
29
+ fi
30
+ }
@@ -92,21 +92,28 @@ if (-not $npmCmd) {
92
92
 
93
93
  $nodeVerStr = (& $nodeCmd.Source --version).Trim()
94
94
  $nodeMajor = [int]($nodeVerStr -replace '^v(\d+)\..*', '$1')
95
- if ($nodeMajor -lt 22) {
95
+ $nodeMinor = [int]($nodeVerStr -replace '^v\d+\.(\d+)\..*', '$1')
96
+ if ($nodeMajor -lt 22 -or ($nodeMajor -eq 22 -and $nodeMinor -lt 5)) {
96
97
  Write-Step 'FAIL' 'Node.js Version' "Node.js >= 22.5.0 required (detected $nodeVerStr)"
97
98
  exit 1
98
99
  }
99
100
 
101
+ $globalModules = (& $npmCmd.Source root --global).Trim()
102
+ if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve the configured npm global root.' }
103
+ & $nodeCmd.Source (Join-Path $RepositoryRoot 'scripts/afyx-local-link-ownership.mjs') $RepositoryRoot $globalModules
104
+ if ($LASTEXITCODE -ne 0) { throw 'Refusing to replace or unlink a foreign npm installation.' }
105
+
100
106
  if ($Uninstall) {
101
107
  Write-Step 'INFO' 'Uninstall' 'Unlinking global afyx-engineering-kit package...'
102
108
  try {
103
109
  Push-Location $RepositoryRoot
104
110
  & $npmCmd.Source unlink --global afyx-engineering-kit 2>&1 | Out-Null
111
+ if ($LASTEXITCODE -ne 0) { throw 'npm unlink failed; installation state must be reviewed.' }
105
112
  Pop-Location
106
113
  Write-Step 'PASS' 'Uninstall' 'Successfully unlinked global afyx-engineering-kit.'
107
114
  } catch {
108
115
  Pop-Location
109
- Write-Step 'WARN' 'Uninstall' "npm unlink notice: $_"
116
+ throw 'npm unlink failed; existing installation was preserved for review.'
110
117
  }
111
118
  exit 0
112
119
  }
@@ -189,5 +196,5 @@ if ($npxVerExit -ne 0 -or $npxHelpExit -ne 0 -or $npxDryExit -ne 0) {
189
196
 
190
197
  Write-Step 'PASS' 'BARE_NPX_ON_WINDOWS' 'Bare "npx afyx-engineering-kit install" resolved offline from temp directory.'
191
198
  Write-Step 'PASS' 'OFFLINE_REGISTRY_ISOLATION' 'Executed with npm_config_offline=true; zero registry queries required.'
192
- Write-Step 'PASS' 'GRAPH_RUNTIME_AVAILABILITY' 'Graph engine and release archives confirmed available.'
199
+ Write-Step 'INFO' 'GRAPH_RUNTIME_AVAILABILITY' 'Not tested by the local-link verifier; use Full runtime acceptance separately.'
193
200
  Write-Step 'PASS' 'LOCAL_BARE_NPX_VERIFIED' 'Local bare NPX resolution setup is healthy and verified.'